/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.x2.modular.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.x2.base.log.BussinessLog;
import com.x2.base.pojo.node.LayuiTreeNode;
import com.x2.base.pojo.node.ZTreeNode;
import com.x2.base.pojo.page.LayuiPageFactory;
import com.x2.base.pojo.page.LayuiPageInfo;
import com.x2.core.base.controller.BaseController;
import com.x2.core.constant.dictmap.DeptDict;
import com.x2.core.constant.factory.ConstantFactory;
import com.x2.core.constant.factory.TreeFactory;
import com.x2.core.exception.enums.BizExceptionEnum;
import com.x2.core.util.ToolUtil;
import com.x2.kernel.model.exception.RequestEmptyException;
import com.x2.kernel.model.response.ResponseData;
import com.x2.kernel.model.response.SuccessResponseData;
import com.x2.modular.system.entity.Dept;
import com.x2.modular.system.entity.User;
import com.x2.modular.system.model.DeptDto;
import com.x2.modular.system.service.DeptService;
import com.x2.modular.system.service.UserService;
import com.x2.modular.system.utils.TreeFilter;
import com.x2.modular.system.warpper.DeptWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 *
 * @author changpeng
 * @Date 2021-01-11
 */
@Controller
@RequestMapping("/dept")
public class DeptController extends BaseController {

    private String PREFIX = "/system/dept/";
    @Autowired
    private DeptService deptService;
    @Autowired
    private UserService userService;

    /**
     * 跳转到部门管理首页
     *
     * @return 页面地址
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "dept.html";
    }

    /**
     * 跳转到添加部门
     *
     * @param parentId:        父部门id
     * @param parentName：父部门名称
     * @param model：请求
     * @return 页面地址
     */
    @RequestMapping("/dept_add")
    public String deptAdd(String parentId, String parentName, Model model) {
        model.addAttribute("parentId", parentId);
        model.addAttribute("parentName", parentName);
        return PREFIX + "dept_add.html";
    }

    /**
     * 跳转到修改部门
     *
     * @param deptId：部门ID
     * @return 修改结果
     */
    @RequestMapping("/dept_update")
    public String deptUpdate(@RequestParam("deptId") Long deptId) {
        if (ToolUtil.isEmpty(deptId)) {
            throw new RequestEmptyException();
        }
        Dept dept = deptService.getById(deptId);
        return PREFIX + "dept_edit.html";
    }


    /**
     * 新增部门
     *
     * @param dept：添加的数据
     * @return 添加结果
     */
    @BussinessLog(value = "添加部门", key = "simpleName", dict = DeptDict.class)
    @RequestMapping(value = "/add")
    @ResponseBody
    public ResponseData add(Dept dept) {
        this.deptService.addDept(dept);
        return SUCCESS_TIP;
    }

    /**
     * 获取所有部门列表
     *
     * @param condition：查询条件
     * @param deptId：        部门id
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "condition", required = false) String condition, @RequestParam(value = "deptId", required = false) Long deptId) {
        Page<Map<String, Object>> list = this.deptService.list(condition, deptId);
        Page<Map<String, Object>> wrap = new DeptWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 获取所有部门列表
     *
     * @param deptId：部门id
     * @return 结果
     */
    @RequestMapping(value = "/getPidsName")
    @ResponseBody
    public ResponseData getPidsName(@RequestParam(value = "deptId", required = false) Long deptId) {
        Dept dept = this.deptService.getById(deptId);
        String[] pids = dept.getPids().split(",");
        String PName = " ";
        for (String item : pids) {
            String pid = item.substring(1, item.length() - 1);
            if (!"0".equals(pid)) {
                Dept deptPid = this.deptService.getById(pid);
                PName += deptPid.getFullName() + " ";
            }
        }
        ResponseData a = new ResponseData();
        a.setData(PName + dept.getFullName());
        return a;
    }

    /**
     * 部门详情
     *
     * @param deptId：部门id
     * @return 部门详情
     */
    @RequestMapping(value = "/detail/{deptId}")
    @ResponseBody
    public Object detail(@PathVariable("deptId") Long deptId) {
        Dept dept = deptService.getById(deptId);
        DeptDto deptDto = new DeptDto();
        BeanUtil.copyProperties(dept, deptDto);
        deptDto.setPName(ConstantFactory.me().getDeptName(deptDto.getPid()));
        if (dept != null) {
            if (dept.getLeaderId() != null) {
                deptDto.setLeaderName(ConstantFactory.me().getUserNameById(dept.getLeaderId()));
            }
        }
        return deptDto;
    }

    /**
     * 修改部门
     *
     * @param dept：数据对象
     * @return 结果
     */
    @BussinessLog(value = "修改部门", key = "simpleName", dict = DeptDict.class)
    @RequestMapping(value = "/update")
    @ResponseBody
    public ResponseData update(Dept dept) {
        deptService.editDept(dept);
        return SUCCESS_TIP;
    }

    /**
     * 删除部门
     *
     * @param deptId：部门id
     * @return 结果
     */
    @BussinessLog(value = "删除部门", key = "deptId", dict = DeptDict.class)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public ResponseData delete(@RequestParam Long deptId) {
        List<Dept> subDepts = deptService.likePids(deptId);
        if (ToolUtil.isNotEmpty(subDepts)) {
            return ResponseData.error(BizExceptionEnum.DEPT_HAS_CHILD_ERROR.getMessage());
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_id userId", "dept_id deptId");
        queryWrapper.eq("dept_id", deptId);
        queryWrapper.ne("status", "DELETED");
        List<Map<String, Object>> userList = userService.listMaps(queryWrapper);

        if (ToolUtil.isNotEmpty(userList)) {
            return ResponseData.error(BizExceptionEnum.DEPT_HAS_USER_ERROR.getMessage());
        }
        deptService.deleteDept(deptId);
        return SUCCESS_TIP;
    }


    @RequestMapping("/getDeptTree")
    @ResponseBody
    public SuccessResponseData getDeptTree() {
        return new SuccessResponseData(this.deptService.getSelectTreeData());
    }

    /**
     * 选择部门
     *
     * @return 页面地址
     */
    @RequestMapping("/chooseDept")
    public String chooseDept() {
        return PREFIX + "chooseDept.html";
    }


    /**
     * 获取部门的tree列表，layuiTree格式
     *
     * @param request: 请求
     * @return 树结果
     */
    @RequestMapping(value = "/layuiTree")
    @ResponseBody
    public List<LayuiTreeNode> layuiTree(HttpServletRequest request) {
        List<ZTreeNode> list = this.deptService.tree();
//        list.add(TreeFactory.createRoot());

        List<LayuiTreeNode> layuiTreeNodes = TreeFactory.convert(list);
        String deptScope = request.getParameter("deptScope");
        List<LayuiTreeNode> resList = TreeFilter.filter(layuiTreeNodes, deptScope);
        return resList;
    }




    /**
     * 获取所有部门列表
     *
     * @param condition
     * @param deptId
     * @return
     */
    @RequestMapping(value = "/deptList")
    @ResponseBody
    public Object deptList(@RequestParam(value = "condition", required = false) String condition, @RequestParam(value = "deptId", required = false) Long deptId) {
        List<Map<String, Object>> recordList = this.deptService.deptList(condition, deptId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> topMap = new HashMap<>(2);
        topMap.put("deptId", 0L);
        topMap.put("simpleName", "顶级");
        resultList.add(topMap);
        resultList.addAll(recordList);
        return resultList;
    }

}
